package com.study.lihan.springmvc.service;


import com.study.lihan.springmvc.bean.MyException;
import com.study.lihan.springmvc.mapper.MainThreadMapper;
import com.study.lihan.springmvc.mapper.ZiThreadMapper;
import com.study.lihan.springmvc.bean.TaskThread;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

@Service
public class ThreadTestServiceImpl  {
    @Autowired
    public MainThreadMapper mainThreadMapper;
    @Autowired
    public ZiThreadMapper ziThreadMapper;

    @Transactional
    public void threadTestTransactional() {
        ExecutorService executorService = Executors.newCachedThreadPool();
        List<Future<String>> resultList = new ArrayList<Future<String>>();
        mainThreadMapper.updateById(1,"main");
        for (int i = 0; i < 1; i++) {
            Future<String> future = executorService.submit(new TaskThread(ziThreadMapper));
            // 将任务执行结果存储到List中
            resultList.add(future);
        }
        executorService.shutdown();
        // 遍历任务的结果
        for (Future<String> fs : resultList) {
            try {
                System.out.println(fs.get());
            } catch (Exception e) {
                throw new MyException("子线程抛出异常了");
            }
        }
    }
}
